var express = require('express');
var router = express.Router();
var path = require('path');
var MongoClient = require('mongodb').MongoClient;
var DB_CONN_STR = "mongodb://localhost:27017/Movie";

/* GET users listing. */
router.get('/', function(req, res, next) {
    res.send('respond with a resource'); //send 发送
});
// router.get('/login', function(req, res, next) {
//     console.log(req.query.email);
//     console.log(req.query.password);
//     res.send('login');
// });

router.post('/login', function(req, res) {
    // console.log(req.body.email); //post获取数据用req.body
    // console.log(req.body.password);
    // console.log(req.param('email'));
    // res.send('login');
    var email = req.body.email;
    var password = req.body.password;
    MongoClient.connect(DB_CONN_STR, function(err, db) {
        if (err) {
            return;
        } else {
            var conn = db.collection('user');
            var data = { email: email, password: password };
           // console.log(data);
            conn.find(data).toArray(function(err, results) {
                //console.log(results);
                if (results.length > 0) {
                    req.session.email = results[0].email;
                    res.redirect('/');
                } else {
                    res.send('登陆失败');
                };
            });
            db.close();
        }
    })
})

router.post('/register', function(req, res, next) {
    var email = req.body.email;
    var password = req.body.password;
    MongoClient.connect(DB_CONN_STR, function(err, db) {
        if (err) {
            return;
        } else {
            var conn = db.collection('user');
            var data = { email: email, password: password };
            //console.log(data);
            conn.insert(data, function(err, results) {
                //console.log(results);
                if(err){
                    return;
                }else{
                    res.redirect('/login');
                }
            });
            db.close()
        }
    })
});
module.exports = router;